/**
 * 车辆排队页面
 * @author
 */

import { ActionModuleBox, CheliangpaiduiBox, HuiseBox, TableBox } from "./style";
import { createRef, useCallback, useEffect, useRef, useState } from "react";
import {
  Button,
  message,
  Select,
  Input,
  Spin,
  Tooltip,
  ConfigProvider,
  Switch,
  Popover,
} from "antd";
import Tuozhuai from "./components/Tuozhuai";
import { SearchProps } from "antd/es/input";
import { ISelectList } from "../../type/antd";
import { handleGetDictionaryItem } from "../../assets/fun/DictionaryItem";
import DengjiAddChangeModule from "./components/DengjiAddChangeModule";
import { IWSData, IWSDataSortList } from "../../type/cheliangpaidui";
import { wsIp } from "../../api/http";
import SearchModule, { IChildRef } from "./components/SearchModule";
import {
  getBaseSortNext,
  getBaseSortSetPdSet,
  postBaseSortGetPdSet,
} from "./api";
import { handleInitVoice } from "../../assets/fun/commit/yuyinbobao";
import { ShengDiv, ShengTanchaung } from "../../assets/style/ShengTanchaung";
import { licensePlateAbbreviations } from "../../assets/data";

const { Search } = Input;

const Cheliangpaidui = () => {
  const ws = useRef<WebSocket | null>(null);
  const bobao = useRef<any>(null);
  const childRef = createRef<IChildRef>();

  const [listData, setListData] = useState<IWSData[]>([]);

  // const listFun = useCallback(async () => {
  //     const { code, msg, data } = (await getBaseLaneList()) as INoFenye<IBaseLaneList>;
  //     if (code === 20000) {
  //         setListData(data);
  //     } else {
  //         message.error(msg);
  //     }
  // }, [setListData]);
  const [addChangeModule, setAddChangeModule] = useState(false); //添加 编辑车辆

  const [carColorList, setCarColorList] = useState<ISelectList[]>([]); // 车辆类型字典项
  const [clickData, setClickData] = useState<IWSDataSortList>(); // 点击clickData
  const [listLoading, setListLoading] = useState(false); //  等待页面更新
  const [searchShow, setSearchShow] = useState(false); //检索车辆信息弹窗
  const [plateColor, setPlateColor] = useState<string>('黄'); //检索车辆信息 - 车牌颜色
  const [chedaoId, setChedaoId] = useState<string>(); // 车道ID
  const [switchPaidui, setSwitchPaidui] = useState<0 | 1>(0); //  获取开关信息
  const [carSheng, setCarSheng] = useState('陕'); // 省
  const [carShengShow, setCarShengShow] = useState(false); // 省弹窗显示与否
  const switchPaiduiFun = useCallback(async () => {
    const { code, msg, data } = (await postBaseSortGetPdSet()) as {
      code: number;
      msg: string;
      data: { isSwitch: 0 | 1 };
    };
    if (code === 20000) {
      setSwitchPaidui(data.isSwitch);
    } else {
      message.error(msg);
    }
  }, []);
  useEffect(() => {
    switchPaiduiFun();
  }, [switchPaiduiFun])

  useEffect(() => {

    let carArr = handleGetDictionaryItem("CPYS");
    let carArr1: ISelectList[] = [];
    carArr.forEach((element) => {
      carArr1.push({
        value: element.label,
        label: element.label,
      });
    });
    setCarColorList(carArr1);
    bobao.current = new SpeechSynthesisUtterance();
    // bobao.current.text = config.text || '轻轻敲醒沉睡的心灵，慢慢张开你的眼睛，看看忙碌的世界，是否依然孤独的转个不停！'; // 文字内容
    bobao.current.lang = "zh-CN"; // 使用的语言:中文
    bobao.current.volume = 1; // 声音音量：1
    bobao.current.rate = 1; // 语速：1
    bobao.current.pitch = 1; // 音高：1
  }, [switchPaiduiFun]);
  const handleChange = (value: string) => {
    setPlateColor(value);
  };

  const ShengHtml = <ShengTanchaung>
    {
      licensePlateAbbreviations.map((item) => {
        return <div
          key={item}
          className={carSheng === item ? 'li-car active' : 'li-car'}
          onClick={() => {
            setCarSheng(item);
          }}
        >
          {item}
        </div>
      })
    }
  </ShengTanchaung>

  const selectAfter = (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <Select
        style={{ width: "7rem" }}
        onChange={handleChange}
        options={carColorList}
        value={plateColor}
      />
      <Popover content={ShengHtml} trigger="click" onOpenChange={(open) => {
        setCarShengShow(open)
      }}>
        <ShengDiv>
          <span style={{ color: !carShengShow ? 'rgba(0, 0, 0, 0.88)' : 'rgba(0, 0, 0, 0.45)' }} >{carSheng}</span><span className="iconfont" style={{ fontSize: '1.2rem', color: 'rgba(0, 0, 0, 0.88)' }}>&#xe661;</span>
        </ShengDiv>
      </Popover>
    </div>

  );
  const onSearch: SearchProps["onSearch"] = (value, _e, info) => {
    if (value === "") {
      message.warning("请输入车牌号");
    } else if (!plateColor) {
      message.warning("请选择车辆颜色");
    } else {
      setSearchShow(true);
      childRef.current?.handleGetData(plateColor, value, carSheng);
    }
  };
  //  获取ws消息
  const initWebSocket = useCallback(() => {
    if (ws.current) {
      ws.current.onmessage = (e) => {
        let allData = JSON.parse(e.data);
        if (allData.type === 1) {
          setListLoading(false);
          setListData(allData.data);
        } else if (allData.type === 0) {
          console.log(allData.data);
          let str = allData.data + allData.data + allData.data;
          // bobao.current.text = allData.data;
          // window.speechSynthesis.speak(bobao.current);
          // window.speechSynthesis.speak(bobao.current);
          handleInitVoice({ text: str });
        }
      };
      ws.current.onclose = (e) => {
        const token = sessionStorage.getItem("token");
        setListLoading(true);
        // console.log(token)
        const wsuri = `${wsIp}/pdList?token=${token}`;
        ws.current = new WebSocket(wsuri);
        initWebSocket();
      };
    }
  }, []);
  useEffect(() => {
    const token = sessionStorage.getItem("token");
    setListLoading(true);
    const wsuri = `${wsIp}/pdList?token=${token}`;
    ws.current = new WebSocket(wsuri);
    initWebSocket();
    return () => {
      if (ws.current && ws.current.close !== null) {
        ws.current.close();
      }
    };
  }, [initWebSocket]);
  // 添加修改回调
  const handleAddChangeCallback = () => {
    setAddChangeModule(false);
    setClickData(undefined);
    setChedaoId(undefined);
  };
  //   搜索结果回调
  const handleSearchCallback = () => {
    setSearchShow(false);
  };
  //  点击呼叫下一辆
  const handleClickHujiao = async (id: string) => {
    const { code, msg } = (await getBaseSortNext({ laneId: id })) as {
      code: number;
      msg: string;
    };
    if (code === 20000) {
      message.success("呼叫成功");
    } else {
      message.error(msg);
    }
  };

  const handleSwitch = async (checked: boolean) => {
    const { code, msg } = (await getBaseSortSetPdSet({
      isSwitch: checked ? 1 : 0,
    })) as { code: number; msg: string };
    if (code === 20000) {
      switchPaiduiFun();
    } else {
      message.error(msg);
    }
  };

  return (
    <CheliangpaiduiBox>
      <div className="title">
        车辆排队
        <Switch
          checked={switchPaidui === 0 ? false : true}
          onChange={(show) => handleSwitch(show)}
          checkedChildren="开启"
          unCheckedChildren="关闭"
        />
      </div>
      <ActionModuleBox>
        <Button
          type="primary"
          icon={<span className="iconfont">&#xe620;</span>}
          onClick={() => setAddChangeModule(true)}
          disabled={switchPaidui === 0}
        >
          排队登记
        </Button>
        <Search
          addonBefore={selectAfter}
          placeholder="搜索车牌号"
          allowClear
          onSearch={onSearch}
          style={{ width: "27.3rem" }}
          disabled={switchPaidui === 0}
        />
      </ActionModuleBox>
      <Spin tip="Loading..." spinning={listLoading}>

        <TableBox>
          {
            switchPaidui === 1 || <HuiseBox />
          }
          <thead>
            <tr className="yijibiaoti">
              <th className="diyige_biaoti"></th>
              {listData.map((item) => (
                <th className="yijibiaoti_xunhuanyangshi" key={item.id}>
                  {item.laneName}
                  <Tooltip title="点击呼叫下一辆">
                    <span
                      className="iconfont"
                      onClick={() => handleClickHujiao(item.id)}
                    >
                      &#xe64e;
                    </span>
                  </Tooltip>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            <tr className="cijibiaoti">
              <th className="diyige_biaoti_ciji">当前车辆</th>
              {listData.map((item) => (
                <th className="erjibiaoti_xunhuanyangshi" key={item.id}>
                  {item.sortList.length > 0 &&
                    item.sortList[0].plateColor + item.sortList[0].licensePlate}
                </th>
              ))}
            </tr>
            <tr>
              <td style={{ borderRight: ".1rem solid #E6EEEC" }}>
                <div className="woshi_td">排队列表</div>{" "}
              </td>
              {listData.map((item) => (
                <td
                  style={{
                    borderRight: ".1rem solid #E6EEEC",
                    verticalAlign: "top",
                  }}
                  key={item.id}
                >
                  <ConfigProvider
                    theme={{
                      components: {
                        Table: {
                          borderColor: "#fff",
                        },
                      },
                    }}
                  >
                    <Tuozhuai
                      listData={item.sortList.length > 1 ? item.sortList : []}
                      setClickData={setClickData}
                      setListLoading={setListLoading}
                      setAddChangeModule={setAddChangeModule}
                      chedaoID={item.laneId}
                      setChedaoId={setChedaoId}
                    />
                  </ConfigProvider>
                </td>
              ))}
            </tr>
          </tbody>
        </TableBox>
      </Spin>
      {/* 登记添加修改弹窗 */}
      <DengjiAddChangeModule
        chedaoId={chedaoId}
        open={addChangeModule}
        clickData={clickData}
        carColorList={carColorList}
        handleCallback={handleAddChangeCallback}
        setListLoading={setListLoading}
      />
      {/* 检索车辆信息弹窗 */}
      <SearchModule
        open={searchShow}
        carColorList={carColorList}
        ref={childRef}
        handleSearchCallback={handleSearchCallback}
        carShengNew = {carSheng}
      />
    </CheliangpaiduiBox>
  );
};

export default Cheliangpaidui;
